package com.douwong.student.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import com.douwong.student.R;
import com.douwong.student.activity.HandWrittenImagView;
import com.douwong.student.adapter.HandWriterRecordAdapter;
import com.douwong.student.application.BaseApplication;
import com.douwong.student.base.BaseFragment;
import com.douwong.student.contant.CommonConfig;
import com.douwong.student.contant.NetConfig;
import com.douwong.student.interfaces.WorkResultNotify;
import com.douwong.student.model.HandWriterData;
import com.douwong.student.model.HandWriterInfo;
import com.douwong.student.model.RequestAction;
import com.douwong.student.popuwindow.ImageUrlShowPopu;
import com.douwong.student.task.HanderWriterListTask;
import com.douwong.student.task.QuestionAnswerListTask;
import com.douwong.student.utils.JsonUtils;
import com.douwong.student.utils.LogUtils;
import com.douwong.student.utils.NetUtils;
import com.douwong.student.utils.ToastUtils;
import com.douwong.student.view.MyCommonCallback;
import com.douwong.student.view.PullToRefreshListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;

import static com.douwong.student.application.BaseApplication.mContext;

/**
 * 手写互动碎片  手写互动记录
 * @author leihuajie
 *
 */
@SuppressLint("ValidFragment")
public class HandExchangeRecordFragment extends BaseFragment {


	private static final String TAG = "HandExchangeRecordFragment";
	private View mContentView;
	private PullToRefreshListView mHand_listview;
	private BaseApplication mApplication;
	private String mStartTime;
	private String mSubjectId;
	private List<HandWriterData.DataEntity.ItemsEntity> mDataList=new ArrayList<>();
	private HandWriterRecordAdapter mHandWriterRecordAdapter;
	private boolean mIsLoading;
	private int mCurrentPage=1;
	private Map<String, Object> mMap;
    private    String studentFileUrl="";
    private ImageUrlShowPopu mImageUrlShowPopu;
    private Intent mIntent;

    @Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mContext = activity;
		mApplication = (BaseApplication) activity.getApplication();
	}
	@Override
	protected View getRootView(LayoutInflater inflater, ViewGroup container) {
		mContentView = inflater.inflate(R.layout.hand_exchange_layout, null);

		mHand_listview = (PullToRefreshListView) mContentView.findViewById(R.id.hand_listview);

		return mContentView;
	}
	IntentFilter mFilter=new IntentFilter(){
		{
			addAction(CommonConfig.CLASS_RECORD_SERACH);
		}
	};

	BroadcastReceiver mReceiver=new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			switch (intent.getAction()) {
				case CommonConfig.CLASS_RECORD_SERACH:
					mStartTime = intent.getStringExtra("start_time");
					mSubjectId = intent.getStringExtra("subjectId");
					break;
			}

		}
	};

	@Override
	protected void initData() {
		super.initData();
		mContext.registerReceiver(mReceiver,mFilter);
		loadData(RequestAction.INIT,1,false);
		mHandWriterRecordAdapter = new HandWriterRecordAdapter(mContext,mDataList);
		mHand_listview.setAdapter(mHandWriterRecordAdapter);
		mMap = new HashMap<>();


	}

	@Override
	protected void initEvent() {
		super.initEvent();
		mHand_listview.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {
			@Override
			public void onRefresh() {

				loadData(RequestAction.REFRESH,1,false);
			}
		});
		mHand_listview.setOnILoadMoreListener(new PullToRefreshListView.OnILoadMoreListener() {
			@Override
			public void onLoadMore() {
				if (!mIsLoading){
					++mCurrentPage;
					loadData(RequestAction.LOADMROE,mCurrentPage,false);
				}

			}
		});

		mHand_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {
				//点击详情
				mMap.clear();
				mMap.put("write_interaction_id",mDataList.get(position-1).getId());
				mMap.put("student_id",BaseApplication.sUserBean.getUserbean().getId()+"");

				NetUtils.Post(NetConfig.HAND_WRITER_EXCHANGE_INFO,mMap,new MyCommonCallback<String>(){

					@Override
					public void onSuccess(String result) {
						super.onSuccess(result);

						HandWriterInfo handWriterInfo = JsonUtils.parseString(result, HandWriterInfo.class);
						if (handWriterInfo!=null){
							if (handWriterInfo.isFlag()){
								if (handWriterInfo.getData()!=null && handWriterInfo.getData().size()==1){
									List<HandWriterInfo.DataEntity> data = handWriterInfo.getData();
                                    String student_file_url = data.get(0).getStudent_file_url();
                                    if (student_file_url==null && student_file_url.equals("")){
                                         studentFileUrl=mDataList.get(position-1).getFile_url();
                                    }else {
                                        studentFileUrl =student_file_url;
                                    }

                                    //显示详情
                                   showImageView(view,student_file_url);
                                }else {
									studentFileUrl=mDataList.get(position-1).getFile_url();
									showImageView(view,studentFileUrl);

								}


							}else {
							ToastUtils.makeText(mContext,handWriterInfo.getMsg());
							}
						}


						LogUtils.i(TAG,"手写互动详情："+result);
					}

					@Override
					public void onError(Throwable ex, boolean isOnCallback) {
						super.onError(ex, isOnCallback);
						LogUtils.i(TAG,"手写互动详情 失败："+ex);
						//ToastUtils.makeText(mContext,"访问网路失败");
                        studentFileUrl=mDataList.get(position-1).getFile_url();
                        showImageView(view,studentFileUrl);
					}
				});



			}
		});
	}

    /**
     * 显示图片
     * @param view
     * @param student_file_url
     */
    private void showImageView(View view, String student_file_url) {
       /* if (mImageUrlShowPopu==null){
            mImageUrlShowPopu = new ImageUrlShowPopu(mContext,student_file_url);
        }else {
            mImageUrlShowPopu.setImageView(student_file_url);
        }

        mImageUrlShowPopu.showAtLocation(view, Gravity.CENTER,0,0);*/

        mIntent = new Intent(mContext, HandWrittenImagView.class);
        mIntent.putExtra("filePath",student_file_url);
        mIntent.putExtra("type","handrecord");
        startActivity(mIntent);

    }

    private void loadData(final RequestAction retention, int currentPage, boolean isSearch){
		HanderWriterListTask handerWriterListTask=new HanderWriterListTask(retention,
				isSearch,mApplication ,new WorkResultNotify< HandWriterData.DataEntity.ItemsEntity>(
		) {
			@Override
			public void notify(int stateCode, List<HandWriterData.DataEntity.ItemsEntity> arryResult) {

				if (RequestAction.INIT==retention){
					//初始化
					//有数据 。     无数据。无网络
					if (stateCode== HanderWriterListTask.REQUESTOK){
						mDataList.addAll(arryResult);

						mHandWriterRecordAdapter.notifyDataSetChanged();
					}else if (stateCode==HanderWriterListTask.NO_NETWOK){
						ToastUtils.makeText(mContext,"请检查网络");
					}

				}else if (RequestAction.REFRESH==retention){
					//刷新
					if (stateCode==HanderWriterListTask.NO_NETWOK){

						ToastUtils.makeText(mContext,"请检查网络");
						mDataList.clear();
						mHand_listview.onRefreshComplete();
						mHandWriterRecordAdapter.notifyDataSetChanged();

					}else if (stateCode==QuestionAnswerListTask.NO_DATA){
						mDataList.clear();
						mHand_listview.onRefreshComplete();
						mHandWriterRecordAdapter.notifyDataSetChanged();

					}else if (stateCode==QuestionAnswerListTask.REQUESTOK){

						mDataList.clear();
						mDataList.addAll(arryResult);
						mHand_listview.onRefreshComplete();
						mHandWriterRecordAdapter.notifyDataSetChanged();

					}


				}else if (RequestAction.LOADMROE==retention){
					//加载更多
					mIsLoading=false;
					if (stateCode==QuestionAnswerListTask.NO_NETWOK){
						--mCurrentPage;
						ToastUtils.makeText(mContext,"请检查网络");
						mHand_listview.completeLoadMore();
						mHandWriterRecordAdapter.notifyDataSetChanged();

					}else if (stateCode== QuestionAnswerListTask.NO_DATA){
						--mCurrentPage;
						mHand_listview.completeLoadMore();
						mHandWriterRecordAdapter.notifyDataSetChanged();

					}else if (stateCode==QuestionAnswerListTask.REQUESTOK){

						mDataList.addAll(arryResult);
						mHand_listview.completeLoadMore();
						mHandWriterRecordAdapter.notifyDataSetChanged();

					}


				}

			}
		});

		handerWriterListTask.executeOnExecutor(Executors.newCachedThreadPool(),mSubjectId,mStartTime,currentPage+"");


	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		if (mReceiver!=null){
			mContext.unregisterReceiver(mReceiver);
		}
	}
}
